package com.youbug.common.config;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.youbug.common.util.UserUtils;
import com.youbug.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;

    /**
     * 排除自动填充的实体
     */
    public static List<String> excludeClasses = new ArrayList<>();

    static {
        //会话表
        excludeClasses.add("com.youbug.kefu.entity.Chat");
        excludeClasses.add("com.youbug.kefu.entity.Message");
        excludeClasses.add("com.youbug.system.entity.Customer");
        excludeClasses.add("com.youbug.system.entity.JobExecHis");
    }

    public boolean isExclude(MetaObject metaObject){
        if(excludeClasses != null && excludeClasses.size() > 0){
            Object originalObject = metaObject.getOriginalObject();
            for(String cls : excludeClasses){
                try {
                    Class<?> clazz = Class.forName(cls);

                    if(originalObject.getClass() == clazz){
                        return true;
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        boolean exclude = isExclude(metaObject);
        if(!exclude){
            String username =  UserUtils.getCurrentUsername();
            this.strictInsertFill(metaObject, "createUser", String.class, username);
            this.strictInsertFill(metaObject, "updateUser", String.class, username);
        }
        log.info("start insert fill ....");
        DateTime date = DateUtil.date();
        this.strictInsertFill(metaObject, "createTime", Date.class, date); // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "updateTime", Date.class, date); // 起始版本 3.3.0(推荐使用)
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        boolean exclude = isExclude(metaObject);
        if(!exclude){

            String username =  UserUtils.getCurrentUsername();
            metaObject.setValue("updateUser", username);
//            this.strictUpdateFill(metaObject, "updateUser", String.class, username);
        }
        log.info("start update fill ....");
        metaObject.setValue("updateTime", DateUtil.date());
//        this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtil.date()); // 起始版本 3.3.0(推荐)
    }
}
